package org.fujene.communicate.deleter;

import java.util.concurrent.LinkedBlockingQueue;

import org.fujene.communicate.lock.IndexableSwitch;
import org.fujene.memman.MemoryManager;

public class DeleterClient implements Runnable{
	private static MemoryManager memman;
	private static LinkedBlockingQueue<DeleterPackage> deleteQueue;
	private static Object deleteBlockade;

	static{
		deleteQueue = new LinkedBlockingQueue<DeleterPackage>();
		deleteBlockade = new Object();
	}

	public DeleterClient(){}

	public static void addToQueue(DeleterPackage pkg){
		deleteQueue.add(pkg);
	}

	public static void property(MemoryManager manager){
		memman = manager;
	}

	public static void waitUntilEmpty(){
		if(!deleteQueue.isEmpty()) try{
			deleteBlockade.wait();
		}catch(InterruptedException e){}
	}

	@Override
	public void run(){
		// Waits until this node turns indexable
		DeleterPackage pkg = null;
		while(true){
			try{
				pkg = deleteQueue.take();
				if(deleteQueue.isEmpty()) synchronized(deleteBlockade){
					deleteBlockade.notifyAll();
				}
			}catch(InterruptedException e1){
				continue;
			}
			try{
				IndexableSwitch.waitIfLocked();
			}catch(InterruptedException e){}

			memman.deleteContent(pkg);
		}
	}

	public static int residue(){
		return deleteQueue.size();
	}
}
